import { defineStore } from 'pinia'

import socket from '@renderer/utlis/socket'
import useChat from './chat'
import { WS_URL } from '@renderer/server/config/config'
import { updateUserInfoApi } from '@renderer/api'
import type { IUserInfo } from '@renderer/api'

const useUser = defineStore('useUser', {
  state: () => ({
    token: JSON.parse(localStorage.getItem('token') || '{}'),
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
    socket: {} as any
  }),
  actions: {
    // 设置token
    setToken(token: string) {
      this.token = token
      localStorage.setItem('token', JSON.stringify(token))
    },
    // 设置用户信息
    setUserInfo(userInfo: object) {
      this.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    // 清除token和用户信息
    clearTokenAndUserInfo() {
      this.token = ''
      this.userInfo = {}
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    },
    // 修改用户信息
    updateUserInfo(userInfo: IUserInfo) {
      return new Promise((resolve) => {
        updateUserInfoApi(userInfo).then((res) => {
          for (const key in this.userInfo) {
            if (Object.prototype.hasOwnProperty.call(this.userInfo, key)) {
              this.userInfo[key] = userInfo[key]
            }
          }
          localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
          resolve(res)
        })
      })
    },
    // 连接socket
    cannectSocket() {
      const chatStore = useChat()
      this.socket = new socket(`${WS_URL}?token=${this.token}`)
      // 获得离线消息
      setTimeout(() => {
        chatStore.getOfflineMessage()
      }, 1000)
    }
  }
})

export default useUser
